/**
 * 21/02/2014
 * 
 * SaleDAO
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.Sale;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of SaleDAO
 * @author Javier Tejedor
 */
public class SaleDAO implements SaleDAOInterface {

	@Autowired
	private SessionFactory sessionFactory;

	/**
	 * Constructor
	 */
	public SaleDAO () {

	}

	/**
	 * returns Hibernate session
	 * @return
	 */
	private Session getSession () {
		return sessionFactory.getCurrentSession();
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#selectById(int)
	 */
	@Transactional(readOnly = true)
	public Sale selectById(int id) {
		Sale shipment = (Sale) getSession().get(Sale.class, id);
		return shipment;
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#selectAll()
	 */
	@Transactional(readOnly = true)
	public List<Sale> selectAll() {
		List<Sale> sale = getSession().createQuery("from Sale").list();
		return sale;
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#selectAllCount()
	 */
	@Transactional(readOnly = true)
	public int selectAllCount() {
		List<Sale> sale = getSession().createQuery("from Sale").list();
		return sale.size();
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#insert(org.cuatrovientos.erp.model.Sale)
	 */
	@Transactional
	public void insert(Sale sale) {
		Integer id = (Integer) getSession().save(sale);
		sale.setId(id);           
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#update(org.cuatrovientos.erp.model.Sale)
	 */
	@Transactional
	public void update(Sale sale) {
		getSession().merge(sale);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#delete(org.cuatrovientos.erp.model.Sale)
	 */
	@Transactional
	public void delete(Sale sale) {
		getSession().delete(sale);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#saveOrUpdate(org.cuatrovientos.erp.model.Sale)
	 */
	@Transactional
	public void saveOrUpdate(Sale sale) {
		getSession().saveOrUpdate(sale);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#deleteById(int)
	 */
	@Transactional
	public void deleteById(int id) {
		Sale sale = (Sale) getSession().load(Sale.class,id);
		getSession().delete(sale);
	}

	/* (non-Javadoc)
	 * @see org.cuatrovientos.erp.dao.SaleDAOInterface#search(java.lang.String)
	 */
	@Transactional(readOnly = true)
	public List<Sale> search(String name) {
		Query query = 
				getSession().
				createQuery("from Sale s where s.name like :name");
		
		query.setParameter("name", "%" + name + "%");

		List<Sale> sale = query.list();

		return sale;
	}

}
